package cn.seapon.talker;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.json.JSONException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import cn.seapon.talker.bean.Account;
import cn.seapon.talker.db.AccountDao;
import cn.seapon.talker.db.MessageEntityDao;
import cn.seapon.talker.infocarrier.Avatars;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.infocarrier.TalkerConfig;
import cn.seapon.talker.net.DownloadUtils;
import cn.seapon.talker.net.TalkerNetOperationUtils;
import cn.seapon.talker.ui.CustomDialog;
import cn.seapon.talker.utils.PackageUtils;

public class SplashActivity extends Activity {
	private static final String TAG = "||___SplashActivity__||";

	private static final int SHOW_DIALOG = 3;
	private static final int NO_DIALOG = 6;
	private static final int CONNECT_FALIED = 4;
	private static final int CONNECT_SUCCESS = 40;
	private static final int CHECK_UPDATE = 412;

	// 显示版本信息
	private TextView tv_splash_version;
	// 显示更新进度
	private TextView tv_update_info;

	// 保存着忽略的版本的信息
	private SharedPreferences sp;

	// 默认登录的账号
	private String defaultAccountName;
	private String defaultAccountPasswd;

	private boolean loginSuccess = false;

	private long startTime;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case SHOW_DIALOG:
				Log.i(TAG, "显示升级的对话框");
				showUpdateDialog();
				break;

			case NO_DIALOG:
				Log.i(TAG, "无需升级！");
				goNext();
				break;

			case CONNECT_SUCCESS:// 进入主页面
				doLogin();
				break;

			case CONNECT_FALIED:
				Log.i(TAG, "连接失败  检查更新！");
				Toast.makeText(SplashActivity.this, "无法连接应用服务器！",
						Toast.LENGTH_SHORT).show();
				checkUpdate();
				break;

			case CHECK_UPDATE:
				checkUpdate();
				break;

			default:
				goNext();
				break;
			}
		}

	};

	/**
	 * 登录操作 完成后检查更新
	 */
	private void doLogin() {
		new Thread() {

			@Override
			public void run() {
				Message mes = Message.obtain();
				if (defaultAccountName != null) {
					// 有保存的账户
					Log.d(TAG, "登录账户和密码为：account:" + defaultAccountName
							+ "  passwd:" + defaultAccountPasswd);
					try {
						if (TalkerNetOperationUtils.loginCheck(
								defaultAccountName, defaultAccountPasswd)) {
							// 登录成功，设置标志位TRUE
							loginSuccess = true;
							mes.what = CHECK_UPDATE;
							handler.sendMessage(mes);
							return;
						}
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}
					loginSuccess = false;
				} else {
					Log.d(TAG, "未保存默认登录的账户和密码.");
				}
				mes.what = CHECK_UPDATE;
				handler.sendMessage(mes);
			}

		}.start();
	}

	protected void goNext() {
		// 结束时间
		long endTime = System.currentTimeMillis();
		// 我们花了多少时间
		long dTime = endTime - startTime;
		// 休眠2000毫秒
		if (dTime < 2000) {// 不到2秒时才做处理
			try {
				Thread.sleep(2000 - dTime);// 2秒减去执行时间 使得刚好2秒
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Intent intent = new Intent();
		if (loginSuccess) {// 登录成功，去MainActivity
			intent.setClass(getApplicationContext(), MainActivity.class);
		} else {
			intent.setClass(getApplicationContext(), LoginActivity.class);
		}
		startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
		tv_update_info = (TextView) findViewById(R.id.tv_update_info);

		startTime = System.currentTimeMillis();
		sp = getSharedPreferences("init_config", Activity.MODE_PRIVATE);
		SharedItems.avatarMap = Avatars.avatarMap;
		SharedItems.messageEntityDao = new MessageEntityDao(
				getApplicationContext());

		init();
	}

	/**
	 * 完成初始化
	 */
	private void init() {
		versionInfoInit();
		savedAccountInit();
		// 开启线程访问网络
		new Thread() {
			@Override
			public void run() {
				Message mes = Message.obtain();
				// 建立套接字
				try {
					TalkerNetOperationUtils.socketConnect();
					mes.what = CONNECT_SUCCESS;
				} catch (Exception e) {
					e.printStackTrace();
					mes.what = CONNECT_FALIED;
					try {
						SharedItems.socket.close();
					} catch (IOException e2) {
						e2.printStackTrace();
					}
				} finally {
					handler.sendMessage(mes);
				}
			}
		}.start();
	}

	/**
	 * 内部广播接受者
	 * 
	 * @author Asuron Created on 2015年1月4日 下午8:17:51
	 */
	public class DownloadProgressReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = getIntent().getExtras();
			int progress = bundle.getInt("current_progress");
			SplashActivity.this.tv_update_info.setVisibility(View.VISIBLE);
			SplashActivity.this.tv_update_info.setText("下载进度: " + progress
					+ "%");
		}

	}

	/**
	 * 检查更新，决定是否显示对话框
	 */
	private void checkUpdate() {
		new Thread() {

			@Override
			public void run() {
				Message mes = Message.obtain();
				try {
					TalkerNetOperationUtils.checkUpdate();
				} catch (Exception e) {
					e.printStackTrace();
					mes.what = NO_DIALOG;
					handler.sendMessage(mes);
					return;
				}
				int gap = SharedItems.newVersionInfos.getVersionCode()
						- SharedItems.packageVersionInfos.getVersionCode();

				if ((gap <= 0)
						|| (SharedItems.newVersionInfos.getVersionCode() == Integer
								.valueOf(sp.getString("IgnoreVersionCode", "0")))) {
					// 版本相同 或者 等于当前忽略的版本，不显示对话框
					mes.what = NO_DIALOG;
				} else {
					// 发送消息后继续往下执行
					mes.what = SHOW_DIALOG;
				}
				// Log.i(TAG,"gap ="+gap+
				// SharedItems.newVersionInfos.getVersionCode() + "   "
				// + SharedItems.packageVersionInfos.getVersionCode()
				// + "   " + sp.getString("IgnoreVersionCode", "0"));
				handler.sendMessage(mes);
			}

		}.start();

	}

	private void showUpdateDialog() {
		CustomDialog.Builder builder = new CustomDialog.Builder(
				SplashActivity.this);
		// builder.setTitle("应用程序升级");
		builder.setMessage(SharedItems.newVersionInfos.getDescribe());
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.d(TAG, "取消了升级");
				dialog.dismiss();
				goNext();
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String apkname = SharedItems.newVersionInfos.getApkFileName();
				String apkurl = TalkerConfig.BASR_APK_URL + apkname;
				DownloadUtils.downloadToInstallApk(SplashActivity.this, apkurl,
						apkname);
				dialog.dismiss();
			}
		});
		builder.setIgnoreButton("忽略", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				SharedPreferences.Editor editor = sp.edit();
				editor.putString("IgnoreVersionCode", ""
						+ SharedItems.newVersionInfos.getVersionCode());
				editor.commit();
				dialog.dismiss();
				goNext();
			}
		});
		builder.create().show();
	}

	/**
	 * 获取版本信息并显示
	 */
	private void versionInfoInit() {
		SharedItems.packageVersionInfos = PackageUtils.getAppVersionInfo(this);
		if (SharedItems.packageVersionInfos == null) {
			Log.e(TAG, "无法获得应用程序信息！");
		}
		tv_splash_version.setText("当前版本："
				+ SharedItems.packageVersionInfos.getVersionName());
	}

	/**
	 * 初始化默认登录的用户信息
	 */
	private void savedAccountInit() {
		SharedItems.accountDao = new AccountDao(getApplicationContext());
		final Account account = SharedItems.accountDao.getDefault();
		if (account != null) {
			defaultAccountName = account.getName();
			defaultAccountPasswd = account.getPasswd();
		} else {
			Log.e(TAG, "无默认保存的数据！");
		}
	}
}
